package com.handpay.framework.utils;

import android.content.Context;

import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.utils.PreferenceManager;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author sxshi on 2016/11/18.
 * @email:emotiona_xiaoshi@126.com
 * @describe:客户端操作时间判断，默认超时时间为10分钟，可以手动设置
 */

public class UserCheckTimeout {
    public static final long TIME_SECONDS = 1 * 1000;
    public static final long TIME_MINUTE = 60 * TIME_SECONDS;
    public static final long TIME_HOUR = 60 * TIME_MINUTE;
    public static final long DEFAULT_TIME_OUT = 10 * TIME_MINUTE;//超时时间10分钟,
    private long mTimeOut;
    private boolean isOpean = false;//是否打开检测
    PreferenceManager preferenceManager;

    public boolean isOpean() {
        return isOpean;
    }

    public void setOpean(boolean opean) {
        isOpean = opean;
    }

    public UserCheckTimeout(Context context) {
        preferenceManager = PreferenceManager.getInstance(context);
        this.mTimeOut = DEFAULT_TIME_OUT;

    }

    public UserCheckTimeout(Context context, long timeOut) {
        preferenceManager = PreferenceManager.getInstance(context);
        this.mTimeOut = timeOut;
    }

    /***
     * 计算时间是否超时
     *
     * @return true 超时  false 未超时
     */
    public boolean isTimeOut() {
        if (!isOpean) {
            return false;
        }
        long currentTimeMillis = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date currentDate = new Date(currentTimeMillis);
        long lastTime = preferenceManager.getLong("Last_Time", 0L);
        if (lastTime > 0) {
            if (currentTimeMillis - lastTime > mTimeOut) {
                HPLog.d(HPLog.SSX_TAG, "已经超时->当前系统时间:" + sdf.format(currentDate));
                HPLog.d(HPLog.SSX_TAG, "已经超时->最后操作时间:" + sdf.format(new Date(lastTime)));
                return true;
            } else {
                HPLog.d(HPLog.SSX_TAG, "没有超时更新最后操作时间:" + sdf.format(new Date(currentTimeMillis)));
                preferenceManager.putLong("Last_Time", currentTimeMillis);
                return false;
            }
        } else {
            Date first = new Date(System.currentTimeMillis());
            HPLog.d(HPLog.SSX_TAG, "第一次记录时间:" + sdf.format(first));
            preferenceManager.putLong("Last_Time", System.currentTimeMillis());
        }
        return false;
    }

    /***
     * 清清除时间
     */
    public void clearTime() {
        HPLog.d(HPLog.SSX_TAG, "清除最后操作时间");
        preferenceManager.remove("Last_Time");
    }
}
